package com.tarena.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.luban.demo.gateway.ex.GatewayException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("AuthenticationFilter...");

        try{
            checkToken(exchange);
        }catch (GatewayException e){
            log.info("异常:{}",e);
            // return writeMessage(exchange,e);
            return Mono.error(e);
        }

        return chain.filter(exchange);
    }

    private Mono<Void> writeMessage(ServerWebExchange exchange,GatewayException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        String result = e.getMessage();
        return response.writeWith(Mono.fromSupplier(
                ()->response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8))));
    }


    private void checkToken(ServerWebExchange exchange) {

        ServerHttpRequest request = exchange.getRequest();
        List<String> token = request.getQueryParams().get("token");

        if(CollectionUtils.isEmpty(token)){
            throw new GatewayException("您没有携带token!");
        }

        String tokenValue = token.get(0);
        if(StringUtils.isEmpty(tokenValue)){
            throw new GatewayException("您的token值为空!");
        }
        boolean b = tokenValue.matches("\\d{10}");
        if(!b){
            throw new GatewayException("您的token值格式不正确!");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
